import Vue from 'vue'
import VueI18n from 'vue-i18n'
import elEnLocale from 'element-ui/lib/locale/lang/en'
import elZhLocale from 'element-ui/lib/locale/lang/zh-CN'

const elLang = {
  zh: elZhLocale,
  en: elEnLocale
}

export const allLangs = [
  { lang: '简体中文', value: 'zh' },
  { lang: 'English', value: 'en' }
]

Vue.use(VueI18n)

const messages = {}

function loadLocaleMessages () {
  const locales = require.context(
    '@/locales',
    true,
    /[A-Za-z0-9-_,\s]+\.json$/i
  )
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]

      messages[locale] = { ...locales(key), ...elLang[locale] }
    }
  })
}

loadLocaleMessages()

// 还没有登录功能保留用户的语言信息。以浏览器为单位，保存选择的语言
let lang = localStorage.getItem('lang')
if (!lang) {
  lang = 'zh'
  localStorage.setItem('lang', 'zh')
}

const i18n = new VueI18n({
  locale: lang,
  fallbackLocale: lang,
  messages,
  silentTranslationWarn: true
})

export const $t = i18n.t.bind(i18n)

Vue.prototype.changeLang = function (lang) {
  // 统一使用此方法来更换语言环境，因为非组件内的国际化不会动态更新，需要刷新页面
  i18n.locale = lang
  localStorage.setItem('lang', lang)
  window.location.reload()
}

export default i18n
